package com.wangqingbo.myspringboot212.controller;

import com.wangqingbo.myspringboot212.entity.ProjectInfo;
import com.wangqingbo.myspringboot212.entity.SysFileInfo;
import com.wangqingbo.myspringboot212.service.ProjectInfoService;
import com.wangqingbo.myspringboot212.service.SysFileService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 项目信息控制器
 */
@Controller
public class ProjectInfoController {

    // 注入一个service的接口
    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired
    private SysFileService fileService;
    /**
     * 获取所有的项目信息
     * @return 项目列表的json数据格式
     */
    @RequestMapping("/getAllProjectInfos")
    @ResponseBody
    public Object getAllProjectInfos()
    {
        // 调用service接口的方法，查询所有的项目信息
        List<ProjectInfo> projectInfoList = projectInfoService.getAllProjects();
        return projectInfoList;
    }

    /**
     * 获取所有的项目信息，并且显示在页面上
     * @return 项目列表的json数据格式
     */
    @RequestMapping("/getAllProjectInfosPage")
    public ModelAndView getAllProjectInfosPage()
    {
        ModelAndView mv = new ModelAndView();
        // 调用service接口的方法，查询所有的项目信息
        List<ProjectInfo> projectInfoList = projectInfoService.getAllProjects();
        // 将查询结果绑定到mv上
        mv.addObject("prjList",projectInfoList);
        // 返回页面
        mv.setViewName("prjList");
        return mv;
    }

    /**
     * 分页查询数据
     * @return
     */
    @RequestMapping("/getProjectInfoByParamsPage")
    @ResponseBody
    public Object getProjectInfoByParamsPage(String projectName, String projectCode, String currentPage, String pageSize)
    {
        // pageSize默认设置为10
        if (pageSize == null || "".equals(pageSize))
        {
            pageSize = "10";
        }
        // 当前页默认设置为1
        if (currentPage == null || "".equals(currentPage))
        {
            currentPage = "1";
        }
        // 调用service接口的方法，查询所有的项目信息
        Map<String,Object> map = projectInfoService.getProjectInfoByParamsPage(projectName, projectCode, Integer.valueOf(currentPage), Integer.valueOf(pageSize));
        return map;
    }

    @RequestMapping("/getProjectInfoByPrjId")
    public ModelAndView getProjectInfoByPrjId(String projectId)
    {
        ModelAndView mv = new ModelAndView();
        // 调用service接口的方法，查询项目信息
        ProjectInfo prjInfo = projectInfoService.getProjectInfoById(projectId);
        // 将查询结果绑定到mv上
        mv.addObject("prj",prjInfo);
        // 返回页面
        mv.setViewName("updatePrj");
        return mv;
    }


    /**
     * 附件上传，使用post请求
     * @param projectId 项目id
     * @param myFile 附件
     * @return
     */
    @RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
    public ModelAndView fileUpload(String projectId, MultipartFile myFile)
    {
        ModelAndView mv = new ModelAndView();
        // 保存附件
        fileService.saveFileInfo(projectId,myFile);

        // 返回页面，重定向
        mv.setViewName("redirect:/prjListAjax.jsp");
        return mv;
    }

    /**
     * 附件下载
     */

    @RequestMapping("/download")
    public ResponseEntity download(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        String fileId = request.getParameter("id");
        SysFileInfo fileInfo = fileService.getFileInfoById(fileId);

        // 用来封装响应头信息
        HttpHeaders responseHeaders = new HttpHeaders();
        // 下载的附件的类型
        responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 下载的附件的名称，这里的附件名称一般是从数据库中取的
        // 为了解决中文名称乱码问题
        String fileName = fileInfo.getOriginalName();
        // 文件路径
        String path = fileInfo.getFilePath();
        // 将下载的文件封装流对象
        File file = new File(path, fileInfo.getFileSaveName());
        // 转码
        fileName = browerCode(fileName, request);
        responseHeaders.setContentDispositionFormData("attachment", fileName);
        try
        {
            /**
             * arg1:需要响应到客户端的数据 arg2:设置本次请求的响应头 arg3:响应到客户端的状态码
             ***/
            return new ResponseEntity(FileUtils.readFileToByteArray(file), responseHeaders, HttpStatus.CREATED);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    private String browerCode(String fileName, HttpServletRequest request) throws Exception
    {
        // 获得请求头中的User-Agent
        String agent = request.getHeader("User-Agent");
        // 根据不同浏览器进行不同的编码
        String filenameEncoder = "";
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filenameEncoder = URLEncoder.encode(fileName, "utf-8");
            filenameEncoder = filenameEncoder.replace("+", " ");
        }
        else
        {
            // 其它浏览器
            filenameEncoder = URLEncoder.encode(fileName, "utf-8");
        }
        return filenameEncoder;
    }
}
